<template>
  <!--  接入产品  -->
  <div class="rule-box">
    <div v-if="$route.query.name" class="back-title">
      <i class="el-icon-arrow-left" @click="$router.go(-1)">返回</i>
    </div>
    <div class="app-container" style="border: 0; background: transparent">
      <el-row class="full-row" :gutter="20">
        <!--部门数据-->
        <el-col class="full-height" :span="5" :xs="24">
          <div class="head-container">
            <!-- draggable -->
            <el-tree
              ref="treeRef"
              :data="productOptions"
              :props="defaultProps"
              :expand-on-click-node="false"
              node-key="id"
              draggable
              :allow-drop="allowDrop"
              highlight-current
              :default-expanded-keys="defaultExpandedKeys"
              :current-node-key="currentKey"
              @node-click="handleNodeClick"
            >
              <span slot-scope="{ data }" class="custom-tree-node">
                <span class="el-tree-nonde_box" :title="data.name">{{ data.name }}</span>
                <span class="tree-icon">
                  <i
                    v-if="data.id == 0 || data.parentId == 0"
                    class="el-icon-plus"
                    @click.stop="handleAddEvent(data)"
                  />
                  <i v-if="data.id != 0" class="el-icon-edit" @click="handleEditEvent(data)" />
                  <i v-if="data.id != 0" class="el-icon-delete" @click="handleDelEvent(data)" />
                </span>
              </span>
            </el-tree>
          </div>
        </el-col>
        <el-col :span="19" :xs="24" class="flex-container">
          <el-form
            v-show="showSearch"
            ref="queryForm"
            :model="queryParams"
            size="small"
            :inline="true"
            @submit.native.prevent
          >
            <el-form-item label="名称" prop="productName">
              <el-input
                v-model="queryParams.productName"
                placeholder="请输入名称"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery"
                @submit.native.prevent
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询 </el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置 </el-button>
            </el-form-item>
          </el-form>

          <el-row :gutter="10" class="mb20 mt2">
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增 </el-button>
            </el-col>
          </el-row>
          <style-type
            v-if="styleType"
            id="styleType"
            :data-list="productList"
            @handleUpdate="handleUpdate"
            @handleDelete="handleDelete"
          />
          <el-table
            v-if="!styleType"
            v-loading="loading"
            :data="productList"
            :header-cell-style="{ background: '#F3F5FC' }"
          >
            <el-table-column label="序号" align="center" width="120">
              <template slot-scope="scop">
                {{ scop.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column label="产品名称" prop="productName" :show-overflow-tooltip="true" />
            <el-table-column label="产品类型" prop="productType" :show-overflow-tooltip="true" />
            <el-table-column label="产品版本" prop="version" width="140" />
            <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="handleUpdate(scope.row, 'table')">编辑 </el-button>
                <el-button size="mini" type="text" @click="handleDelete(scope.row, 'table')">删除 </el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.current"
            :limit.sync="queryParams.size"
            @pagination="getList"
          />

          <!-- 添加或修改产品配置对话框 -->
          <editDialog ref="editRef" :title="title" :form-data="formData" @handleSubmit="handleSubmit" />
          <editProductType
            ref="editProductTypeRef"
            :title="productTypeTitle"
            :form-data="productTypeForm"
            @handleSubmit="handleTypeSubmit"
          />
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import editDialog from '../components/productEditor'
import { treeselect, list, delProduct, ProductType, delProductType, productInfo } from '@/api/milkyway/accessProduct'
import styleType from '../components/styleType'
import editProductType from './productType'

export default {
  name: 'ProductTemplate',
  components: { editDialog, styleType, editProductType },
  data() {
    return {
      defaultExpandedKeys: ['0'],
      styleType: true,
      formData: {},
      currentKey: '0',
      // 遮罩层
      loading: true,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 列表数据
      productList: [],
      // 弹出层标题
      title: '',
      productTypeTitle: '',
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 产品类型列表
      productOptions: [],
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        productName: undefined,
        productCode: 0,
        parentId: '-1'
      },
      // 表单参数
      form: {},
      // 产品类型表单
      productTypeForm: {
        name: undefined,
        code: undefined,
        parentId: undefined,
        id: undefined
      },
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  created() {
    this.getTreeselect()
    this.getList()
  },
  mounted() {
    console.log(this.$router)
    const that = this
    window.addEventListener('message', function(e) {
      const settingData = e.target.localStorage['layout-setting']
      that.$store.commit('settings/WATCH_SETTING', settingData)
    })
  },
  methods: {
    /** 查询产品列表 */
    getList() {
      this.loading = true
      // this.$loading()
      list(this.queryParams).then((res) => {
        this.productList = res.list
        this.total = res.total
        // this.$loading().close()
        this.loading = false
        this.queryParams.scrollToTop = false
      })
    },
    /** 查询产品类型树结构 */
    getTreeselect() {
      treeselect({ type: 'product' }).then((response) => {
        this.productOptions = response
      })
    },
    /** 添加产品类型 */
    handleAddEvent(data) {
      this.productTypeForm = {
        parentId: data.id,
        name: undefined,
        code: undefined,
        id: undefined
      }
      this.productTypeTitle = '新增'
      this.$refs.editProductTypeRef.show()
    },
    /** 修改产品类型 */
    handleEditEvent(data) {
      ProductType(data.id).then((res) => {
        this.productTypeForm = {
          parentId: res.parentId,
          name: res.name,
          code: res.code,
          id: res.id
        }
        this.productTypeTitle = '编辑'
        this.$refs.editProductTypeRef.show()
      })
    },
    /** 删除产品类型 */
    handleDelEvent(data) {
      this.$modal
        .confirm('是否确认删除当前数据项？')
        .then(function() {
          return delProductType(data.id)
        })
        .then(() => {
          this.getList()
          this.getTreeselect()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },

    /** 刷新列表 */
    handleSubmit(id) {
      if (id) {
        this.defaultExpandedKeys = [id]
      }
      this.queryParams.parentId = '-1'
      this.queryParams.productCode = 0
      this.getTreeselect()
      this.getList()
    },
    handleTypeSubmit() {
      this.getTreeselect()
    },
    /** 树点击方法 */
    handleNodeClick(data) {
      this.queryParams.productCode = data.id
      this.queryParams.parentId = data.parentId
      this.queryParams.current = 1
      this.getList()
    },
    startLoading() {
      return this.$loading({
        target: document.querySelector('#styleType'),
        fullscreen: false
      })
    },
    endLoading(loading) {
      loading.close()
    },
    // 表单重置
    reset() {
      if (this.$refs.menu !== undefined) {
        this.$refs.menu.setCheckedKeys([])
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.loading = true
      this.queryParams.current = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      if (this.queryParams.parentId) {
        if (this.queryParams.parentId === '0') {
          this.formData = { parentId: this.queryParams.productCode }
        } else {
          this.formData = {
            parentId: this.queryParams.parentId,
            productCode: this.queryParams.productCode
          }
        }
      }
      this.$refs.editRef.show(this.productOptions, this.formData)
      this.title = '添加'
    },
    /** 修改按钮操作 */
    handleUpdate(row, type) {
      productInfo(type ? row.id : row.object.id).then((res) => {
        this.formData = {
          id: res.id,
          productCode: res.productCode,
          productName: res.productName,
          productType: res.productType,
          version: res.version,
          companyLogo: res?.companyLogo || undefined,
          parentId: res.parentId
        }
        this.$refs.editRef.show(this.productOptions, this.formData)
        this.title = '编辑'
      })
    },
    /** 删除按钮操作 */
    handleDelete(row, type) {
      this.defaultExpandedKeys = [row.object.productCode]
      const name = type ? row.productName : row.object.productName
      this.$modal
        .confirm('是否确认删除当前数据项？')
        .then(function() {
          return delProduct(type ? row.id : row.object.id)
        })
        .then(() => {
          const totalPage = Math.ceil((this.total - 1) / this.queryParams.size)
          this.queryParams.current = this.queryParams.current > totalPage ? totalPage : this.queryParams.current
          this.getList()
          this.getTreeselect()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    /** 拖拽时判定目标节点能否被放置 */
    allowDrop(draggingNode, dropNode, type) {
      if (draggingNode.parent.id == dropNode.parent.id) {
        console.log(type)
        return type != 'inner'
      } else {
        return false
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.app-container {
  height: 100%;
  padding: 0;

  .full-row {
    height: 100%;
    margin: 0 !important;
  }
}

.head-container {
  height: 100%;
}

.full-height {
  height: 100%;
  padding: 20px;
  border-right: 1px solid rgba(0, 0, 0, 0.08);
}

.head-container {
  width: 100%;
  overflow: auto;
}
.el-tree-node__content{
  width:100% !important;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  width:calc(100% - 60px);
  overflow:hidden;
  .el-tree-nonde_box{
    text-overflow: ellipsis;
    display: block;
    overflow: hidden;
  }
  .tree-icon {
    i {
      margin: 0 2px;
    }
  }
}
.flex-container {
  display: flex;
  flex-direction: column;
  height: calc(100% - 20px);
  padding:0 20px;
  .card-wk {
    flex: 1;
    overflow: auto;
  }
}
</style>
